var action;
var db;
var idClicked;


function connectDB(act) {
	action = act;
	db = window.openDatabase("JapaneseBasic", "1.0", "Japanese Database",500000);
	db.transaction(getFavourite, errorCB);
}

function errorCB(err) {
	alert("Error processing SQL: " + err.code);
}

function successCB() {
	db.transaction(getFavourite, errorCB);
}

function getFavourite() {
	switch(action){
	case 'vocabulary':
		db.transaction(getFavouriteVocabulary, errorCB);
		break;
	case 'kanji':
		db.transaction(getFavouriteKanji, errorCB);
		break;
	case 'reading':
		db.transaction(getFavouriteReading, errorCB);
		break;
	case 'grammar':
		db.transaction(getFavouriteGrammar, errorCB);
		break;
	case 'listening':
		db.transaction(getFavouriteListening, errorCB);
		break;
	}
}


//  XU LY SHOW,REMOVE,NOTE DANH SACH VOCABULARY YEU THICH
function getFavouriteVocabulary(tx) {
	var sql = "SELECT v_id,v_word,v_hiragana,v_mean_kanji,v_mean_en,v_mean_vi,v_lesson_id,v_note,v_favourite,v_dataversion_id,le_id, le_title " +
		      " FROM vocabulary " +
		      " INNER JOIN lesson" + 
		      " ON vocabulary.v_lesson_id = lesson.le_id" +
		      " WHERE v_favourite = 1 " + 
		      " ORDER BY v_lesson_id,v_word ASC  ";
    tx.executeSql(sql, [], showFavouriteVocabulary);
}

function showFavouriteVocabulary(tx, results) {
	var len = results.rows.length;
	if (len > 0) {
		for (var i = 0; i < len; i++) {
			var data = results.rows.item(i);
			$('#vocabulary-favourite').append('<li vocabularyid="'+data.v_id+'" style="height: 90px;" class="ui-li-static ui-body-inherit ui-first-child ui-last-child"><fieldset class="ui-list-a"><div class="ui-block-a" style="position: absolute; top: 7px; right: 60px; left: 45px;">'
					+ '<h5 class="kanji" style=" margin-left: -20px;float: left; display: block">'+data.v_word+'</h5>'
					+ '<h3  style="float: right; font-size: 12px; margin-top: 15px; display: block">'
					+ '<span class="mean_kanji" style="text-transform: uppercase;">'+data.v_mean_kanji+'</span> <br><br>'
					+ '<span class="mean_en" >'+data.v_mean_en+'</span></h3>'
					+ '<p class="hiragana" style="float: left; clear: both; margin-left: -20px;margin-top: -35px; display: block;"><span>&nbsp;</span><span>'+data.v_hiragana+'</span></p>'
					+ '<p class="mean_vi" style="float: left; clear: both; margin-left: -20px;margin-top: -10px; display: block;"> <span>&nbsp;</span><span>'+data.v_mean_vi+'</span></p>'
					+ '<p class="lesson" style="float: left; clear: both; margin-left: -20px;display:block;"><span>&nbsp;</span><span>'+data.le_title+'</span></p></div>'
					+ '<div class="ui-block-b" style="position: absolute; top: -2px; right: 5px;"><div data-role="controlgroup" data-type="vertical" style="width: 30px;" class="ui-controlgroup ui-controlgroup-vertical ui-corner-all">'
					+ '<div class="ui-controlgroup-controls ">'
					+ '<a href="#remove-favourite" onclick="removeVocabularyFavourite('+data.v_id+')" data-theme="a" data-rel="popup" data-position-to="window" data-transition="pop" data-role="button" data-iconpos="notext" class="ui-link ui-btn ui-icon-minus ui-btn-icon-notext ui-shadow ui-corner-all ui-first-child" role="button">remove favourite</a>'
					+ '<a noteID="'+data.v_id+'" id="noteDialog" href="#write-note"  onclick="writeNote('+data.v_id+');" data-rel="popup" data-position-to="window" data-transition="pop" data-role="button" data-iconpos="notext" data-icon="edit" class="ui-link ui-btn ui-icon-edit ui-btn-icon-notext ui-shadow ui-corner-all ui-last-child" role="button">Edit</a>'
					+ '</div></div></div></fieldset></li>');
		}
		
	} else {
		$('#vocabulary-favourite').append(
				'<div style="margin: 20px; 20px;">Không có dữ liệu</div>');
	}
}

//remove favourite in vocabulary 
function removeVocabularyFavourite(id){
	$("#removeFavouriteOK").click(function(){
		//$( this ).unbind( event );
		db.transaction(function(tx) {
			var sql = "UPDATE vocabulary SET v_favourite = 0 WHERE v_id = " + id;
	    tx.executeSql(sql, [], function(tx, results) {
	    	$('li[vocabularyid="' + id + '"]').remove();
	    	$('#vocabulary-favourite').listview('refresh');
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
   }, function(tx, error) {
	alert("Processing favourite error: " + error);
   });
});
}

function writeNote(id){
	idClicked = id;
	//set id cho moi textarea
	$('#note-content').attr('textareaid',idClicked);
	$('textarea[textareaid="' + idClicked + '"]').val('');
	
	//lay ve v_note cua vocabulary co v_id = id
	this.db.transaction(function(tx) {
		var sql = "SELECT v_note FROM vocabulary WHERE v_id =? ";
		tx.executeSql(sql, [ idClicked ], function(tx, results) {
			//$('#note-content').val(results.rows.item(0).v_note);
			$('#note-content[textareaid="'+idClicked+'"]').val(results.rows.item(0).v_note);
			
			//when click ok button
			$("#writeNoteOK").click(function(){
				db.transaction(function(tx) {  
					var textareIDSelecting = $('#note-content').attr('textareaid');
					if (textareIDSelecting == idClicked) {
						var inputText = $('#note-content[textareaid="'+idClicked+'"]').val(); // chi lay ve du lieu trong textarea co noteid = id
						//kiem tra xem inputText co giong vs chuoi ban dau khong --> th use mo len n khong them bat cu character nao ca ma press ok button
						if (inputText.toString() !=  results.rows.item(0).v_note) {
							var sql = "UPDATE vocabulary SET v_note = '"+inputText+"' WHERE v_id = " + idClicked;
				            return false;
					        tx.executeSql(sql, [], function(tx, results) {
					        	successUpdateNoteToast();
					        }, function(tx, error) {
						        alert("Error: " + error);
					        });
						}
					}
		        }, function(tx, error) {
			         alert("Processing favourite error: " + error);
		        });
		    });
		});
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
}

function successUpdateNoteToast(){
	var msg = new Android_Toast({content: 'Đã cập nhật ghi chú thành công'});
}

function errorUpdateNoteToast(){
	//var toast2 = new Android_Toast({content: 'Bỏ đánh dấu yêu thích', duration: 4000, position: 'top'});
	var msg = new Android_Toast({content: 'Write note unsuccess'});
}




//XU LY SHOW,REMOVE DANH SACH KANJI YEU THICH
function getFavouriteKanji(tx) {
	var sql = "SELECT k_id, k_kanji ,k_mean_kanji, k_mean_en ,k_mean_vi " +
    " FROM kanji WHERE k_favourite = 1 ORDER BY k_id ASC ";
    tx.executeSql(sql, [], showFavouriteKanji);
}
			
function showFavouriteKanji(tx, results) {
	var len = results.rows.length;
	if (len > 0) {
		for (var i = 0; i < len; i++) {
			var data = results.rows.item(i);
			$('#kanji-favourite').append('<li kanjiid="'+data.k_id+'"><a  href="kanji_detail.html?id='+data.k_id+'" data-ajax="false" data-direction="reverse"class="ui-btn ui-btn-icon-right ui-icon-carat-r">' 
					+ '<span id="wrap"><span class="kanji" style="font-weight: bold; font-size: 18px; margin-left: -50px;">'+data.k_kanji+'</span>'
					+ '<span class="mean_kanji" style="text-transform: uppercase; font-weight: bold; font-size: 16px;">'+data.k_mean_kanji+'</span>'
					+ '<span class="mean_vi">'+data.k_mean_vi+'</span> '
					+ '<span class="mean_en">'+data.k_mean_en+'</span></span></a>'
					+ '<div class="ui-block-b"style="position: absolute; top: -2px; right: 5px;">'
					+ '<a href="#remove-favourite" onclick="removeKanjiFavourite('+data.k_id+')" data-theme="a" data-rel="popup" data-position-to="window" data-transition="pop" data-role="button" data-iconpos="notext" class="ui-link ui-btn ui-icon-minus ui-btn-icon-notext ui-shadow ui-corner-all ui-first-child" role="button">remove favourite</a></li>');
		}
	} else {
		$('#kanji-favourite').append(
				'<div style="margin: 20px; 20px;">Không có dữ liệu</div>');
	}
}

function removeKanjiFavourite(id){
	$("#removeFavouriteOK").click(function(){
		db.transaction(function(tx) {
			var sql = "UPDATE kanji SET k_favourite = 0 WHERE k_id = " + id;
	    tx.executeSql(sql, [], function(tx, results) {
	    	$('li[kanjiid="' + id + '"]').remove();
	    	$('#kanji-favourite').listview('refresh');
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
   }, function(tx, error) {
	alert("Processing favourite error: " + error);
   });
});
}




//XU LY SHOW,REMOVE DANH SACH GRAMMAR YEU THICH
function getFavouriteGrammar(tx) {
	var sql = "SELECT g_id, g_title, g_mean, g_lesson_id " +
    " FROM grammar WHERE g_favourite = 1 ORDER BY g_id ASC ";
    tx.executeSql(sql, [], showFavouriteGrammar);
}

function showFavouriteGrammar(tx, results) {
	var len = results.rows.length;
	if (len > 0) {
		for (var i = 0; i < len; i++) {
			var data = results.rows.item(i);
			$('#grammar-favourite').append('<li grammarid="'+data.g_id+'"><a href="grammar_detail.html?leid=' + data.g_lesson_id + '&id='+ data.g_id+ '" data-ajax="false" data-direction="reverse" class="ui-btn ui-btn-icon-right ui-icon-carat-r" style="font-weight:normal;font-family:Times New Roman, Times, serif;"> '
					+ data.g_title + '</a>'
					+ '<div class="ui-block-b"style="position: absolute; top: -2px; right: 5px;">'
					+ '<a href="#remove-favourite" onclick="removeGrammarFavourite('+data.g_id+')" data-theme="a" data-rel="popup" data-position-to="window" data-transition="pop" data-role="button" data-iconpos="notext" class="ui-link ui-btn ui-icon-minus ui-btn-icon-notext ui-shadow ui-corner-all ui-first-child" role="button">remove favourite</a></li>');
		}
	} else {
		$('#grammar-favourite').append(
				'<div style="margin: 20px; 20px;">Không có dữ liệu</div>');
	}
}

function removeGrammarFavourite(id){
	$("#removeFavouriteOK").click(function(){
		db.transaction(function(tx) {
			var sql = "UPDATE grammar SET g_favourite = 0 WHERE g_id = " + id;
	    tx.executeSql(sql, [], function(tx, results) {
	    	$('li[grammarid="' + id + '"]').remove();
	    	$('#grammar-favourite').listview('refresh');
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
   }, function(tx, error) {
	alert("Processing favourite error: " + error);
   });
});
}


//XU LY SHOW,REMOVE DANH SACH READING YEU THICH
function getFavouriteReading(tx) {
	var sql = "SELECT r_id, r_title, r_lesson_id " +
    " FROM reading WHERE r_favourite = 1 ORDER BY r_id ASC ";
    tx.executeSql(sql, [], showFavouriteReading);
}

function showFavouriteReading(tx, results) {
	var len = results.rows.length;
	if (len > 0) {
		for (var i = 0; i < len; i++) {
			var data = results.rows.item(i);
			$('#reading-favourite').append('<li readingid="'+data.r_id+'"><a href="reading_detail.html?leid=' + data.r_lesson_id + '&id='+ data.r_id+ '" data-ajax="false" data-direction="reverse" class="ui-btn ui-btn-icon-right ui-icon-carat-r" style="font-weight:normal;font-family:Times New Roman, Times, serif;"> '
					+ data.r_title + '</a>'
					+ '<div class="ui-block-b"style="position: absolute; top: -2px; right: 5px;">'
					+ '<a href="#remove-favourite" onclick="removeReadingFavourite('+data.r_id+')" data-theme="a" data-rel="popup" data-position-to="window" data-transition="pop" data-role="button" data-iconpos="notext" class="ui-link ui-btn ui-icon-minus ui-btn-icon-notext ui-shadow ui-corner-all ui-first-child" role="button">remove favourite</a></li>');
		}
	} else {
		$('#reading-favourite').append(
				'<div style="margin: 20px; 20px;">Không có dữ liệu</div>');
	}
}

function removeReadingFavourite(id){
	$("#removeFavouriteOK").click(function(){
		db.transaction(function(tx) {
			var sql = "UPDATE reading SET r_favourite = 0 WHERE r_id = " + id;
	    tx.executeSql(sql, [], function(tx, results) {
	    	$('li[readingid="' + id + '"]').remove();
	    	$('#reading-favourite').listview('refresh');
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
   }, function(tx, error) {
	alert("Processing favourite error: " + error);
   });
});
}



//XU LY SHOW,REMOVE DANH SACH LISTENING YEU THICH
function getFavouriteListening(tx) {
	//alert('tam thoi dang selsect li_favourite = 0');
	var sql = "SELECT li_id, li_title, li_lesson_id " +
    " FROM listening WHERE li_favourite = 1 ORDER BY li_id ASC ";
    tx.executeSql(sql, [], showFavouriteListening);
}

function showFavouriteListening(tx, results) {
	var len = results.rows.length;
	if (len > 0) {
		for (var i = 0; i < len; i++) {
			var data = results.rows.item(i);
			$('#listening-favourite').append('<li listeningid="'+data.li_id+'"><a href="listening.html?id='+ data.li_id+ '" data-ajax="false" data-direction="reverse" class="ui-btn ui-btn-icon-right ui-icon-carat-r" style="font-weight:normal;font-family:Times New Roman, Times, serif;"> '
					+ data.li_title + '</a>'
					+ '<div class="ui-block-b"style="position: absolute; top: -2px; right: 5px;">'
					+ '<a href="#remove-favourite" onclick="removeListeningFavourite('+data.li_id+')" data-theme="a" data-rel="popup" data-position-to="window" data-transition="pop" data-role="button" data-iconpos="notext" class="ui-link ui-btn ui-icon-minus ui-btn-icon-notext ui-shadow ui-corner-all ui-first-child" role="button">remove favourite</a></li>');
		}
	} else {
		$('#listening-favourite').append(
				'<div style="margin: 20px; 20px;">Không có dữ liệu</div>');
	}
}


function removeListeningFavourite(id){
	$("#removeFavouriteOK").click(function(){
		db.transaction(function(tx) {
			var sql = "UPDATE listening SET li_favourite = 0 WHERE li_id = " + id;
	    tx.executeSql(sql, [], function(tx, results) {
	    	$('li[listeningid="' + id + '"]').remove();
	    	$('#listening-favourite').listview('refresh');
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
   }, function(tx, error) {
	alert("Processing favourite error: " + error);
   });
});
}










//Xu ly add/remove favourite o cac man hinh : kanji_detail, grammar_detai, listening_detail,...
function processFavourite(prefix,tblName,id) {
	var favouriteValue;
	this.db.transaction(
            function (tx) {
            	var sql = "SELECT "+prefix+"favourite AS favouriteItem FROM "+tblName+" WHERE "+prefix+"id =? ";
                tx.executeSql(sql, [id], function (tx, results) {
                    var len = results.rows.length;
                    if(results.rows.item(0).favouriteItem == 1){//hien tai dang favourited -> unfavourite
                    	favouriteValue = 0 ;
                    }else{
                    	favouriteValue = 1;
                    }
                    db.transaction(
                            function (tx) {
                            	var sql2 = "UPDATE "+tblName+" SET "+prefix+"favourite = " + favouriteValue + " WHERE "+prefix+"id = ? " ;
                                tx.executeSql(sql2, [id], function (tx, results) {
                                	if (favouriteValue == 1) {
                                		//cap nhat icon
                                		$('[task="favouriteTask"]').attr("id","addFavourite");
                                		addFavouriteToast();
                            		}else{
                            			$('a[task="favouriteTask"]').attr("id"," ");
                            			removeFavouriteToast();
                            		}
                                });
                            },function (tx, error) {
                                alert("Processing favourite error: " + error);
                     });
                });
            },function (tx, error) {
                alert("Processing favourite error: " + error);
            });
}



function addFavouriteToast(){
	var msg = new Android_Toast({content: 'Đã đánh dấu yêu thích'});
}

function removeFavouriteToast(){
	//var toast2 = new Android_Toast({content: 'Bỏ đánh dấu yêu thích', duration: 4000, position: 'top'});
	var msg = new Android_Toast({content: 'Bỏ đánh dấu yêu thích'});
}

function errorFavouriteToast(){
	//var toast2 = new Android_Toast({content: 'Bỏ đánh dấu yêu thích', duration: 4000, position: 'top'});
	var msg = new Android_Toast({content: 'Add favourite error'});
}
